<?php

namespace App\Http\Controllers;

use App\Exceptions\BusinessException;
use App\Models\Notice;
use App\Models\Order;
use App\Services\CompanyService;
use App\Services\NoticeService;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 编辑信息
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function editInfo(Request $request)
    {
        $uid = $request->uid;
        $name = $request->post('name');
        $avatar = $request->post('avatar');
        $sex = $request->post('sex');
        $birth = $request->post('birth');
        UserService::getInstance()->editInfo($uid, $name, $avatar, $sex, $birth);

        return $this->success();
    }

    /**
     * 编辑手机号
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function editPhone(Request $request)
    {
        $uid = $request->uid;
        $country = $request->post('country');
        $phone = $request->post('phone');
        $code = $request->post('code');
        UserService::getInstance()->editPhone($uid, $country, $phone);

        return $this->success();
    }

    /**
     * 用户中心
     * @param Request $request
     * @return JsonResponse
     */
    public function userCenter(Request $request)
    {
        $uid = $request->uid;
        // 用户信息
        $data['user_info'] = UserService::getInstance()->info($uid);
        // 待付款订单
        $data['wait_pay_order_num'] = Order::query()->where(['user_id' => $uid, 'state' => Order::STATE_WAIT_PAY])->count('id');
        // 待使用订单
        $data['wait_use_order_num'] = Order::query()->where(['user_id' => $uid, 'state' => Order::STATE_WAIT_USE])->count('id');
        // 我的消息
        $data['message_num'] = 0;
        // 公司信息
        $data['company_info'] = CompanyService::getInstance()->info();
        return $this->success($data);
    }

    /**
     * 用户信息
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function userInfo(Request $request)
    {
        $uid = $request->uid;
        $data = UserService::getInstance()->info($uid);

        return $this->success($data);
    }

    /**
     * 通知列表
     * @param Request $request
     * @return JsonResponse
     */
    public function noticeList(Request $request)
    {
        $uid = $request->uid;
        $page = $request->input('page', 1);
        $pageSize = $request->input('psize', 10);
        $type = $request->input('type', Notice::TYPE_ORDER);
        $data = NoticeService::getInstance()->list($page, $pageSize, $uid, $type);

        return $this->success($data);
    }
}
